package servlet;

import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @Title: login
 * @Author 郑雨杭
 * @Package servlet
 * @Date 2024/7/29 23:03
 * @description:
 */
@WebServlet("/login")
public class login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserDao userDao = new UserDao();
        /*if(username!=null&&password!=null
                &&username.length()!=0&&password.length()!=0
                &&userDao.login(username, password)){
            resp.sendRedirect(req.getContextPath()+"/blog_list.html");
        }else{
            resp.sendRedirect(req.getContextPath()+"/login.html");
        }*/
        if(username==null||password==null ||username.length()==0||password.length()==0){
            resp.sendRedirect(req.getContextPath()+"/login.html");
        }
        User user = userDao.findByName(username);
        if(user==null){
            resp.sendRedirect(req.getContextPath()+"/login.html");
            return;
        }
        if(password.equals(user.getPassword())){
            HttpSession session = req.getSession(true);
            session.setAttribute("user",user);
            resp.sendRedirect(req.getContextPath()+"/blog_list.html");
        }else{
            resp.sendRedirect(req.getContextPath()+"/login.html");
        }
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if(session==null){
            resp.setStatus(403);
            return;
        }
        User user =(User) session.getAttribute("user");
        if(user==null){
            resp.setStatus(403);
            return;
        }
        resp.setStatus(200);
    }
}
